#include "pch.h"
#include <strsafe.h>
#include "Utils.h"

//-------------------------------------------------------------------
// ShowErrorMessage
//
// Displays an error message.
//-------------------------------------------------------------------

void ShowErrorMessage(PCWSTR format, HRESULT hrErr)
{
	HRESULT hr = S_OK;
	WCHAR msg[MAX_PATH];

	hr = StringCbPrintf(msg, sizeof(msg), L"%s (hr=0x%X)", format, hrErr);

	if (SUCCEEDED(hr))
	{
		AfxMessageBox(msg);
	}
}

CString GetComExceptionMessage(HRESULT hr)
{
	CString strMessage;
	strMessage.Empty();
	if (FAILED(hr))
	{
		IErrorInfoPtr ipErrorInfo;
		BSTR description(_bstr_t(_T("")));
		GetErrorInfo(NULL, &ipErrorInfo);
		if (ipErrorInfo)
		{
			ipErrorInfo->GetDescription(&description);
			strMessage = description;
			USES_CONVERSION;
			strMessage.Format(_T("%s"), (CString)strMessage);
		}
		else
		{
			LPVOID pvMsgBuf = NULL;
			LPCTSTR pszMsg = NULL;
			if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL, (DWORD)hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&pvMsgBuf, 0, NULL))
			{
				pszMsg = (LPTSTR)pvMsgBuf;
				strMessage.Format(_T("%s"), pszMsg);
			}
		}
	}
	return strMessage;
}
